#include <iostream>
#include <cassert>
#include <vector>
#include <unistd.h>
#include <string>
#include "Task.hpp"
using namespace std;

const int gnum = 5;
Task t;

//使得每个子进程与对应管道匹配
class endPoint{
public:
    pid_t _child_id;
    int _write_fd;

    endPoint(int id, int fd)
    :_child_id(id)
    ,_write_fd(fd){
    }

    ~endPoint(){
    }
};

void waitCommand(){
    while(true){
        int command = 0;
        int n = read(0, &command, sizeof(int));
        if(n == sizeof(int)){
            t.Execute(command);
        }
        else
            break;
    }
}

void createProcesses(vector<endPoint> *end_points){
    for (int i = 0; i < gnum; i++){
        int pipefd[2] = {0};
        int n = pipe(pipefd);
        assert(n ==0);
        (void)n;

        pid_t id = fork();
        assert(id != -1);
        if(id == 0){
            close(pipefd[1]);
            //dup2(pipefd[0], 0);
            //waitCommand();

            while(true){
                int command = 0;
                int n = read(pipefd[0], &command, sizeof(int));
                if(n == sizeof(int)){
                    t.Execute(command);
                }
                else
                    break;
            }

            close(pipefd[0]);
            exit(0);
        }
        close(pipefd[0]);
        end_points->push_back(endPoint(id, pipefd[1]));
    }
}

int main(){
    vector<endPoint> end_points;
    createProcesses(&end_points);
    int num = 0;
    while(true){
        //选择任务
        int command = COMMAND_LOG;
        //选择进程
        int index = rand() % end_points.size();
        //下发任务
        write(end_points[index]._write_fd, &command, sizeof(command));

        sleep(1);
    }
    return 0;
}
